<?php
// +--------------------------------------------------------------------------
// | ZAIYOUDAO [ 载攸道 先顺得常 ] <http://www.zaiyoudao.com>
// +--------------------------------------------------------------------------
// | Copyright © 2009-2016 载攸道 版权所有 <TEL:17090888854>
// +--------------------------------------------------------------------------
// | Project: YiPHP [ 我会的仅仅是偷懒！ ] <http://www.yiphp.com>
// +--------------------------------------------------------------------------
// | Author: 牛很多戒很多不戒 <n@isdce.com> <http://juexue.wang>
// +--------------------------------------------------------------------------

/**
 * WeiXin
 */
namespace Addon\WeiXin\Controller;
use Addon\WeiXin\Controller\CommonController;

/**
 * 微信公共
 */
class PublicController extends CommonController {
    
	//微信登录
	public function Login(){
		
		//授权网址
		$oauth_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/Home/OAuth/Login/Addon/WeiXin.html';
		//登录网址
		$login_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/Home/Mall/Index/Addon/MallTemplateHome.html';

		//如果没有获得code跳转获得code去
		if(!I('param.code')){
	
			redirect("$oauth_url", 0,'');
		
		}
		
		$weixin = getWeiXinConf();
		//获得信息
		$access = \Org\Net\Wechat\Oauth::token($weixin['weixinpay_appid'],$weixin['weixinpay_appsecret']);
		$user = \Org\Net\Wechat\Oauth::info($access['access_token'],$access['openid']);
		
		//判断是否是用户
		$map['weixin_openid'] = $user['openid']; 
		
		$m_common_user = M('common_user');
		
		$data = $m_common_user->where($map)->find();
		
		//是用户授权
		if($data){
			
			cookie('uid',$data['id'],3600*24*7);

		}else{
			
			$m_common_user_for_group = M('common_user_for_group');
			
			$data['nickname'] = $user['nickname']; //昵称
			$data['sex'] = $user['sex']; //性别 1男 2女
			$data['province'] = $user['province']; //地区
			$data['country'] = $user['country']; //国家
			$data['img'] = $user['headimgurl'];//头像
			$data['weixin_unionid'] = $user['unionid']; //唯一ID
			
			$data['weixin_openid'] = $user['openid']; //openid 
			$data['username'] = $user['openid']; //填充姓名
			$data['tel'] = $user['openid']; //填充电话
			$data['email'] = $user['openid']; //填充邮箱
			
			$data['password'] = md5(time()); //填充密码
			$data['create_time'] = time(); //创建时间
			$data['create_ip'] = get_client_ip(); //创建IP
			$data['status'] = 1; //用户状态
			
			//创建用户
			$uid = $m_common_user->add($data);
			
			//关联用户
			$gdata['uid'] = $uid;
			$gdata['gid'] = 9; //商城用户
			$gdata['type'] = 2;
			$gdata['status'] = 1;
			
			$m_common_user_for_group->add($gdata);
			
			cookie('uid',$uid,3600*24*7);
		}
		
		redirect("$login_url", 0,'');
		
		
	}
	

	
	
}